#include "defines.h"
#include "transition.h"
#include "transitionTarget.h"
#include <boost/algorithm/string.hpp>
#include <algorithm>

TransitionTarget::TransitionTarget( std::string id, TransitionTarget *parent):
  id(id),
  parent(parent),
  m_active(false)
{
}

TransitionTarget::~TransitionTarget()
{
}

void TransitionTarget::onEntry(void)
{
  std::cout << "onentry" << std::endl;
}

void TransitionTarget::onExit(void)
{
  std::cout << "onexit" << std::endl;
}

TransitionList* TransitionTarget::getTransitionList(std::string const event)
{
  TransitionList *matchingTransitions = new TransitionList;
  TransitionList::iterator it;

  for (it = transitions.begin(); it != transitions.end(); ++it)
    {
      if (event == it->getEvent())
	matchingTransitions->push_back(*it);
    }
  return matchingTransitions;
  // for (int i = 0; i < transitions.size(); i++) {
  //   Transition t = (Transition) transitions.get(i);
  //   if ((event == null && t.getEvent() == null)
  // 	|| (event != null && event.equals(t.getEvent()))) {
  //     if (matchingTransitions == null) {
  // 	matchingTransitions = new ArrayList();
  //     }
  //     matchingTransitions.add(t);
  //   }
  // }

}
void TransitionTarget::setInitial(std::string const target)
{
    //std::cout << id << " set initial " << target << std::endl;
  boost::split(initialTransition, target, boost::is_any_of("\t "));
  //std::cout << id << ": Print initial vector\n";
  //PrintVector<std::string>(std::cout, initialTransition);
}

bool TransitionTarget::start(strset &cfg)
{
  // std::cout << "starting " << id << std::endl;
  // std::cout << "initial " << std::endl;
  // PrintVector<std::string>(std::cout, initial, " ");
  // std::cout << "initial Tr " << std::endl;
  // PrintVector<std::string>(std::cout, initialTransition);
  // std::cout << "---------------\n";

  // std::copy(initialTransition.begin(), initialTransition.end(),
  // 	    std::inserter(cfg));
  cfg.insert(initialTransition.begin(), initialTransition.end());
  return (initialTransition.size() > 0);
}


bool TransitionTarget::isAncestor(TransitionTarget *s)
{
    bool result = false;
    TargetList::iterator i;

    if (!s || children.empty())	// don't bother.
	return result;

    i = find_if(children.begin(), children.end(), eq(s));

    if (i !=  children.end())
	result = true;
    else
    {
	for(i=children.begin(); i!=children.end(); ++i)
	{
	    result = (*i)->isAncestor(s);
	    if (result)
		break;
	}
    }
    return result;
}

ostream &operator<<(ostream& s, const TransitionTarget* c)
{
    if (c)
	s << c->id << endl;
    else 
	s << "(null)" << endl;
    return s;
}
